package controllers

import (
	"eth_block_lottery/abi"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/gorilla/websocket"
	"math/big"
	"time"
)

// 存放客户端的连接
var clients = make(map[*websocket.Conn]bool)

// 升级为ws
var upgrade = websocket.Upgrader{}

var accountChan = make(chan map[string]interface{})

type LotteryController struct {
	beego.Controller
}

func (c *LotteryController) Betting() {
	username := c.GetString("username")
	password := c.GetString("password")
	redOne, _ := c.GetInt64("red_one")
	redTwo, _ := c.GetInt64("red_two")
	redThree, _ := c.GetInt64("red_three")
	redFour, _ := c.GetInt64("red_four")
	redFive, _ := c.GetInt64("red_five")
	redSix, _ := c.GetInt64("red_six")
	blue, _ := c.GetInt64("blue")
	nums := []*big.Int{
		big.NewInt(redOne),
		big.NewInt(redTwo),
		big.NewInt(redThree),
		big.NewInt(redFour),
		big.NewInt(redFive),
		big.NewInt(redSix),
		big.NewInt(blue),
	}
	err := abi.Bet(username, password, nums)
	if err != nil {
		c.Ctx.ResponseWriter.WriteHeader(400)
		c.Data["json"] = map[string]interface{}{"msg": "投注失败"}
		c.ServeJSON()
		return
	}
	c.Ctx.ResponseWriter.WriteHeader(200)
	c.Data["json"] = map[string]interface{}{"msg": "投注成功"}
	c.ServeJSON()
	return
}

func (c *LotteryController) Periods() {
	periods, err := abi.GetPeriods()
	if err != nil {
		c.Ctx.ResponseWriter.WriteHeader(400)
		c.Data["json"] = map[string]interface{}{"msg": "获取彩票期数失败"}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{"periods": periods}
	c.ServeJSON()
	return
}

func (c *LotteryController) GetAccountAndNums() {
	ws, err := upgrade.Upgrade(c.Ctx.ResponseWriter, c.Ctx.Request, nil)
	if err != nil {
		abi.Log.Error("ws connect failed", err)
	}
	retMap := map[string]interface{}{
		"account": "阿斯顿发送到发",
	}
	//连接放到clients总
	clients[ws] = true
	for {
		time.Sleep(3 * time.Second)
		//todo 从智能合约中获取投注信息写入到通道中
		//todo 从通道中取出来写入ws
		for client := range clients {
			err := client.WriteJSON(retMap)
			if err != nil {
				abi.Log.Error("ws write json failed", err)
				delete(clients, client)
				client.Close()
			}
		}
	}
}
